package com.lambkit.module.cms.web.interceptor;

import com.lambkit.common.LambkitConsts;
import com.lambkit.common.util.StringUtils;
import com.lambkit.module.cms.Cms;
import com.lambkit.module.cms.core.template.TemplateManager;
import com.lambkit.module.cms.rpc.model.CmsMenu;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;

import java.util.List;

/**
 * 公共拦截器
 */
public class CmsWebInterceptor implements Interceptor {

    //private static final Log LOG = Log.getLog(CmsWebInterceptor.class);

	@Override
	public void intercept(Invocation inv) {
		Controller controller = inv.getController();
		// 过滤ajax
        if (null != controller.getHeader("X-Requested-With") && "XMLHttpRequest".equalsIgnoreCase(controller.getHeader("X-Requested-With"))) {
        	System.out.println("X-Requested-With: " + TemplateManager.me().getCurrentWebPath());
        	inv.invoke();
        } else {
        	controller.set(LambkitConsts.ATTR_TEMPLATE_PATH, controller.getRequest().getContextPath() + TemplateManager.me().getCurrentWebPath());
        	controller.set("URL", Cms.config().getUrl());
            // 菜单
            List<CmsMenu> menus = CmsMenu.service().find(CmsMenu.sql().example().setOrderBy("orders asc"));
            controller.set("menus", menus);
            controller.set("curl", StringUtils.urlDecode(controller.getRequest().getRequestURI()));
    		inv.invoke();
        }
	}
}
